<?php

namespace App\Models;


use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class News extends Base
{

    // 用户管理
    protected $table = 'news';

    // 缓存字段，用于搜索绑定的字段
    protected $cacheFields = ['id', 'uid', 'cate_id', 'from_site', 'from_channel', 'verify', 'is_top', 'is_push',];


    // 添加
    //public function oneAdd($data = [])
    public function publish($uid, $data, $topids = [], $stockIds = [])
    {

        // 验证信息
        $rules  = $this->fieldRule();
        $result = $this->validator($data, $rules, ['id' => '修改的用户编号']);
        if($result === false){
            return false;
        }

        // 获取所有的来源站点信息
        $domainDb  = new SiteDomain();
        $allStocks = $domainDb->isCache(true)->getList();
        foreach($allStocks as $_stock){
            $_name = $_stock['name'];
            if(strpos($data['content'], $_name) !== false){
                //$stocks[] = ['domain_id' => $_stock['id'], 'ctime' => LARAVEL_TIME]; // 'news_id' => $newsId,
                $stockIds[] = $_stock['id'];
            }
        }


        if(empty($uid)){
            return $this->return_false('请指定发帖用户!');
        }
        if(empty($data['content'])){
            return $this->return_false('请填写内容!');
        }

        // 模型
        $siteDb    = new NewsSite();
        $descDb    = new NewsDesc();
        $addonDb   = new NewsAddon();
        $userDb    = new User();
        $ntDb      = new NewsTopic();
        $topicMain = new Topic();

        // 参数
        $news_id = $data['id'] ?? 0;
        $uid     = $data['uid'] ?? 0;
        // 文章：添加属性 + 添加日志
        if($data['channel'] == 'news'){
            // 添加属性表
            $data3 = [
                'date'        => date("Y-m-d"),
                'week'        => date("YW"),   // 年份-周数
                'day'         => date("Ymd"),
                'month'       => date("Ym"),
                'cate_id'     => $data['cate_id'] ?? 0,
                'uid'         => $uid,
                'is_original' => $data['is_original'] ?? 0,
                'verify'      => $data['verify'] ?? 1,
            ];
            $addonDb->fill($data3);
        }

        // 如果是修改 查询内容信息
        $info     = [];
        $descInfo = [];
        if($news_id){
            $info = $this->isCache(true)->oneFind(["id" => $data['id']]);
            $info = is_object($info) ? $info->toArray() : $info;
            if(empty($info)){
                return $this->return_false('你要修改的内容不存在!');
            }
            if($info['verify'] == -1){
                return $this->return_false('你要修改的内容已经删除!');
            }
            if($info['is_complain']){
                return $this->return_false('你要修改的内容被投诉!');
            }

            // 以前的用户
            $old_uid = $info['uid'];
            // 以前的话题
            $ftWhere   = ['news_id' => $news_id];
            $oldTocic  = $ntDb->isCache(true)->getList($ftWhere, 0);
            $oldTocIds = array_column($oldTocic, 'topic_id');
            // 以前的站点
            $stWhere = ['news_id' => $news_id];
            $oldSock = $domainDb->isCache(true)->getList($stWhere, 0);
            $oldSids = array_column($oldSock, 'domain_id');

            // 发帖数量
            $userDataAdd  = ['news_no' => DB::raw('news_no'.'+1'), "publish_no" => DB::raw('publish_no+1'), 'mtime' => LARAVEL_TIME];
            $userCacheAdd = ['news_no' => '+1', "publish_no" => '+1'];
            $relayDataAdd = ['relay_no' => DB::raw("relay_no+1"), 'mtime' => LARAVEL_TIME];
            $relayDataDsc = ['relay_no' => DB::raw("relay_no-1"), 'mtime' => LARAVEL_TIME];
            $userDataDsc  = ['news_no' => DB::raw('news_no'.'-1'), "publish_no" => DB::raw('publish_no-1'), 'mtime' => LARAVEL_TIME];
            $userCacheDsc = ['news_no' => '-1', "publish_no" => '-1'];
            $topicDataAdd = ['news_no' => DB::raw('news_no'.'+1'), 'mtime' => LARAVEL_TIME];
            $topicDataDsc = ['news_no' => DB::raw('news_no'.'-1'), 'mtime' => LARAVEL_TIME];

            // 是否改变
            $changeUser = $old_uid != $uid;
            $addTopIds  = array_diff($topids, $oldTocIds, [0]); // 添加的话题
            $desTopIds  = array_diff($oldTocIds, $topids, [0]); // 减少的话题
            $addSids    = array_diff($stockIds, $oldSids, [0]);  // 添加的股票
            $desSids    = array_diff($oldSids, $stockIds, [0]);  // 减少的股票
            // 添加阿特的用户 添加引用的话题
            $addUserData  = [];
            $addTopData   = [];
            $addStockData = [];
            if($addTopIds){
                foreach($addTopIds as $_topid){
                    $addTopData[] = ['news_id' => $data['id'], 'topic_id' => $_topid, 'ctime' => LARAVEL_TIME];
                }
            }
            if($addSids){
                foreach($addSids as $_sid){
                    $addStockData[] = ['news_id' => $data['id'], 'domain_id' => $_sid, 'ctime' => LARAVEL_TIME];
                }
            }

            // 数据
            $articleData = $this->filterField($data);
            $descData    = $descDb->filterField($data);
            if($descData){
                $descInfo = $descDb->isCache(true)->oneFind(['news_id' => $news_id]);
            }
        } else{
            $changeUser   = true;
            $changeRelay  = true;
            $old_relay_id = 0;
            $relayDataDsc = [];
            // 整理数据
            //   阿特的用户 与 转发的数据
            $userDataAdd  = ['news_no' => DB::raw('news_no'.'+1'), "publish_no" => DB::raw('publish_no+1'), 'mtime' => LARAVEL_TIME];
            $userDataDsc  = [];
            $userCacheAdd = ['news_no' => '+1', "publish_no" => '+1'];
            $relayDataAdd = ['relay_no' => DB::raw("relay_no+1"), 'mtime' => LARAVEL_TIME];

            // 模型数据
            $articleData = $this->filterField($data);
            $descData    = $descDb->filterField($data);
            $this->fill($articleData);
            $descDb->fill($descData);
        }


        unset($data['host'], $data['guest'], $data['voice_text']);
        // 保存数据
        DB::beginTransaction();
        try{
            /*// 如果有置顶
            if($is_top){
                // 取消其他置顶
                $result = $this->where(['is_top' => $is_top])->update(['is_top' => 0]);
            }*/

            // 修改
            if($news_id){
                $newId = $data['id'];
                unset($data['id'], $descData['id'], $data['channel']);
                // 主表
                if($articleData){
                    $result = $this->where('id', $newId)->update($articleData);
                }
                // 附表
                if($descData){
                    $result = $descDb->where('news_id', $newId)->update($descData);
                }

                // 话题的数量
                if($addTopIds){
                    $topicMain->whereIn('id', $addTopIds)->update($topicDataAdd);
                }
                if($desTopIds){
                    $topicMain->whereIn('id', $desTopIds)->update($topicDataDsc);
                }
                // 引用的话题
                if($desTopIds){
                    $ntDb->whereIn('topic_id', $desTopIds)->where('news_id', $newId)->delete();
                }
                if($addTopData){
                    $ntDb->insert($addTopData);
                }

                // 股票信息
                if($desSids){
                    $siteDb->whereIn('domain_id', $desSids)->where('news_id', $data['id'])->delete();
                }
                if($addStockData){
                    $siteDb->insert($addStockData);
                }
            } else{
                // 添加
                $this->save();
                $newId = $this->id;
                // 详情表
                $descDb->news_id = $newId;
                // 整理
                $result = $descDb->save();

                // 附表+日志
                if($data['channel'] == 'news'){
                    $addonDb->news_id = $newId;
                    // 保存浏览日志
                    $result = $addonDb->save();
                }

                // 添加的时候，没有 news_id 只能在事务内部添加修改
                // 话题的数量
                $topicData = [];
                if($topids){
                    foreach($topids as $topicId){
                        $topicData[] = ['news_id' => $newId, 'topic_id' => $topicId, 'ctime' => LARAVEL_TIME];
                        // 文章数量：话题
                        $topicMain->where('id', $topicId)->update(['news_no' => DB::raw('news_no'."+1")]);
                    }
                    // 文章的话题
                    $result = $ntDb->insert($topicData);
                }

                // 股票信息
                if($stockIds){
                    foreach($stockIds as $_sid){
                        $fStockData[] = ['news_id' => $newId, 'domain_id' => $_sid, 'ctime' => LARAVEL_TIME];
                    }
                    $result = $siteDb->insert($fStockData);
                }
            }


            // 更新用户发帖数量
            if($changeUser){
                if($userDataAdd){
                    $userDb->where('id', $uid)->update($userDataAdd);
                }
                if($userDataDsc){
                    $userDb->where('id', $old_uid)->update($userDataDsc);
                }
            }

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 组合用于删除的缓存
        $data['topic_id'] = $topids;
        if(empty($data['uid'])){
            $data['uid'] = $uid;
        }

        // 缓存操作
        $this->deleteCacheShow($data, $info);
        $userDb->deleteCacheShow(['id' => $uid]);
        $topicMain->deleteCacheShow(['id' => $topids]);
        $descDb->deleteCacheShow($data, $descInfo);
        if(!empty($oldTocIds)){
            $topicMain->deleteCacheShow(['id' => $oldTocIds]);
        }
        if(!empty($old_uid)){
            $userDb->deleteCacheShow(['id' => $old_uid]);
        }

        return $this->id;
    }

    // 修改
    // TODO 栏目话题可以是多个的数组，也可以是单个字符串（不能是多个组合的字符串）
    public function _oneEdit($where, $data)
    {
        // 查询
        $info = $this->isCache(true)->oneFind($where);  // ->recycle()
        if(empty($info)){
            return $this->return_false('你要修改的数据不存在！！');
        }

        $info    = is_object($info) ? $info->toArray() : $info;
        $news_id = $info['id'];
        // 模型
        $descDb  = new NewsDesc();
        $addonDb = new NewsAddon();
        $topicDb = new NewsTopic();
        $cateDb  = new NewsCate();


        // 以前的数据 与 现在的数据
        $old_is_original = $info['is_original'];
        $old_uid         = $info['uid'];
        $is_original     = $data['is_original'] ?? null;
        $uid             = $data['uid'] ?? null;

        // 数据
        $articleData = $this->filterField($data);
        $descData    = $descDb->filterField($data);
        $descInfo    = [];
        if($descData){
            $descInfo = $descDb->isCache(true)->oneFind(['news_id' => $news_id]);
        }

        // 属性表改变
        $addonData = false;
        $isChange  = ((!is_null($is_original)) && ($is_original != $old_is_original)) || ((!is_null($uid)) && ($uid != $old_uid));
        if($isChange){
            $addonData = ['cate_id' => 0, 'is_original' => $is_original, 'uid' => $uid,];
        }

        // 文章话题数据
        // 以前的数据 与 现在的数据 （话题是多个）
        $cateMain      = new SiteCate();
        $topicMain     = new Topic();
        $userMain      = new User();
        $old_topic_ids = $info['topic_ids'];
        $old_cate_ids  = $info['cate_ids'];
        $topic_ids     = $data['topic_ids'] ?? [];
        $cate_ids      = $data['cate_ids'] ?? [];
        $addTopicIds   = $delTopicIds = false;
        $addCateIds    = $delCateIds = false;

        // 组合用于删除的缓存
        $data['cate_id']  = array_merge($old_cate_ids, $cate_ids);
        $data['topic_id'] = array_merge($old_topic_ids, $topic_ids);

        // 栏目的变化整理
        $addCate = [];
        $delCate = [];
        if($cate_ids && ($cate_ids != $old_cate_ids)){
            $addCateIds = array_diff($cate_ids, $old_cate_ids);  // 这些话题文章数量+1
            $delCateIds = array_diff($old_cate_ids, $cate_ids);  // 这些话题文章数量-1
            if($addCateIds){
                foreach($addCateIds as $_cateId){
                    if($_cateId){
                        $addCate[] = ['news_id' => $news_id, 'ctime' => LARAVEL_TIME, 'cate_id' => $_cateId,];
                    }
                }
            }
            if($delCateIds){
                foreach($delCateIds as $_cateId){
                    $delCate[] = ['news_id' => $news_id, 'cate_id' => $_cateId,];
                }
            }
        }
        // 话题的变化整理
        $addTopic = [];
        $delTopic = [];
        if($topic_ids && ($topic_ids != $old_topic_ids)){
            $addTopicIds = array_diff($topic_ids, $old_topic_ids);  // 这些话题文章数量+1
            $delTopicIds = array_diff($old_topic_ids, $topic_ids);  // 这些话题文章数量-1
            if($addTopicIds){
                foreach($addTopicIds as $_topicId){
                    if($_topicId){
                        $addTopic[] = ['news_id' => $news_id, 'ctime' => LARAVEL_TIME, 'topic_id' => $_topicId,];
                    }
                }
            }
            if($delTopicIds){
                foreach($delTopicIds as $_topicId){
                    $delTopic[] = ['news_id' => $news_id, 'topic_id' => $_topicId,];
                }
            }
        }

        // 日志
        $nickname = $data['nickname'];
        $content  = $nickname.'与'.date("Ymd H:i:s").'修改文章';
        $data6    = ['uid' => $data['adminId'] ?? 0, 'news_id' => $news_id, 'nickname' => $nickname, 'operate' => 'edit_article', 'content' => $content,];
        $logDb->fill($data6);


        // 文章数量
        $addNumData = ['news_no' => DB::raw("news_no+1"), 'publish_no' => DB::raw("publish_no+1"),];
        $decNumData = ['news_no' => DB::raw("news_no-1"), 'publish_no' => DB::raw("publish_no-1"),];

        // 保存数据
        DB::beginTransaction();
        try{
            /*// 如果有置顶
            if($is_top){
                // 取消其他置顶
                $result = $this->where(['is_top' => $is_top])->update(['is_top' => 0]);
            }*/

            // 主表
            if($articleData){
                $result = $this->where('id', $news_id)->update($articleData);
            }
            // 附表
            if($descData){
                $result = $descDb->where('news_id', $news_id)->update($descData);
            }

            // 属性表
            if($addonData){
                $result = $addonDb->where('news_id', $news_id)->update($addonData);;
            }
            // 添加文章话题表
            if($addTopic){
                $result = $topicDb->insert($addTopic);
            }
            // 删除文章话题表
            if($delTopicIds){
                $result = $topicDb->where('news_id', $news_id)->whereIn('topic_id', $delTopicIds)->delete();
            }
            // 话题文章数量
            if($addTopicIds){
                $result = $topicMain->whereIn('id', $addTopicIds)->update($addNumData);
            }
            if($delTopicIds){
                $result = $topicMain->whereIn('id', $delTopicIds)->update($decNumData);
            }

            // 添加文章栏目表
            if($addCate){
                $result = $cateDb->insert($addCate);
            }
            // 删除文章栏目表
            if($delCateIds){
                $result = $cateDb->where('news_id', $news_id)->whereIn('cate_id', $delCateIds)->delete();
            }
            // 栏目文章数量
            if($addCateIds){
                //$result = $cateMain->whereIn('id', $addCateIds)->update($addNumData);
            }
            if($delCateIds){
                //$result = $cateMain->whereIn('id', $delCateIds)->update($decNumData);
            }

            // 用户文章数量
            if($old_uid != $uid){
                $result = $userMain->where('id', $uid)->update($addNumData);
                $result = $userMain->where('id', $old_uid)->update($decNumData);
            }

            // 添加操作日志
            $result = $logDb->save();

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 缓存操作
        $this->deleteCacheShow($info, $data);
        $descDb->deleteCacheShow($descInfo);
        $topicMain->deleteCacheShow(['id' => $delTopicIds]);
        $topicMain->deleteCacheShow(['id' => $addTopicIds]);
        $cateMain->deleteCacheShow(['id' => $delCateIds]);
        $cateMain->deleteCacheShow(['id' => $addCateIds]);
        if($old_uid != $uid){
            $userMain->deleteCacheShow(['id' => $uid]);
            $userMain->deleteCacheShow(['id' => $old_uid]);
        }

        return $result;
    }

    // 详情
    public function oneFind($where, $order = "id DESC")
    {
        // 获取缓存
        $is_cache = $this->is_cache || $this->bang;
        $args     = compact('where', 'order');
        $info     = null;
        if($is_cache){
            $cacheName = $this->cacheKey('show', $args);
            $info      = $this->cacheClass()->getCache($cacheName);
        }
        // 检查是否已经绑定
        if($info){
            $this->checkBangShow($info, $cacheName);
        }
        // 查询
        if(empty($info)){
            //  查询
            $query = $this->where($where);
            if(is_array($order)){
            } else{
                $order = explode(" ", $order);
                $query = $query->orderby($order[0], $order[1]);
            }
            $info = $query->first(); // ->recycle()
            if(empty($info)){
                return $this->return_false('数据不存在！！');
            }

            // 查询附件
            $addon = (new NewsAddon())->where('news_id', $info->id)->first();
            // 查询属性
            $desc = (new NewsDesc())->where('news_id', $info->id)->first();
            $desc = $desc ? $desc->toArray() : [];
            unset($desc['id']);

            // 附件组合
            $info->addon = [];
            if($addon){
                $info->addon = $addon->toArray();
            }

            // 组合
            $info = $info->toArray();
            $info = array_merge($desc, $info);

            // 保存为缓存
            if($is_cache){
                $this->addCacheShow($info, $cacheName, $info);
            }
        }


        // 组合话题
        //$topic    = (new NewsTopic())->where('news_id', $info['id'])->get()->toArray();
        $topic    = (new NewsTopic())->bangField(['news_id'])->getList(['news_id' => $info['id']], 0);
        $topicIds = array_column($topic, 'topic_id');
        $topics   = (new Topic())->isCache(true)->getListInIds($topicIds);
        if(empty($topics)){
            $topics = [];
        }
        $info['topic']     = array_values($topics);
        $info['topic_ids'] = $topicIds;

        // 组合阿特的用户
        $users = (new NewsUser())->bangField(['news_id'])->getList(['news_id' => $info['id']], 0);
        $uIds  = array_column($users, 'uid');
        $users = (new User())->isCache(true)->getListInIds($uIds);
        if(empty($users)){
            $users = [];
        }
        $info['users']    = array_values($users);
        $info['user_ids'] = $uIds;

        // 阿特的用户
        //$cate    = (new NewsCate())->where('news_id', $info['id'])->get()->toArray();
        //$cate    = (new NewsCate())->bangField(['news_id'])->getList(['news_id' => $info['id']], 0);
        //$cateIds = array_column($cate, 'cate_id');
        if($info['channel'] == 'news'){
            //$cates = (new SiteCate())->isCache(true)->getListInIds($cateIds);
            $cate = (new SiteCate())->isCache(true)->getOneById($info['cate_id']);
        } elseif($info['channel'] == 'need'){
            //$cates = (new NeedCate())->isCache(true)->getListInIds($cateIds);
            $cate = (new NeedCate())->isCache(true)->getOneById($info['cate_id']);
        } elseif($info['channel'] == 'event'){
            //$cates = (new EventCate())->isCache(true)->getListInIds($cateIds);
            $cate = (new EventCate())->isCache(true)->getOneById($info['cate_id']);
        }
        if(empty($cates)){
            $cates = [];
        }
        if(!empty($cate)){
            $info['cate'] = $cate;
        }


        // 后台编辑
        $info['user'] = [];
        if($info['uid']){
            $info['user'] = (new User())->isCache(true)->getOneById($info['uid']);
        }

        return $info;
    }

    // 获取多条数据+翻页
    public function listPage($where = [], $page = 1, $rows = 10, $order = "id DESC")
    {
        // 获取缓存
        $bang     = $this->bang;
        $is_cache = $this->is_cache || $bang;
        $args     = compact('where', 'page', 'rows', 'order');
        if($is_cache){
            $cacheName = $this->cacheKey('lists', $args);
            $cacheData = $this->cacheClass()->getCache($cacheName);
            if(!empty($cacheData)){
                // 检查是否已经绑定
                if(($cacheData) && (!empty($cacheData['list']))){
                    $this->checkBangList($cacheData['list'], $cacheName);
                }

                return $cacheData;
            }
        }

        // 字段
        $fields    = $this->inFields;
        $outFields = $this->outFields;
        if(empty($fields)){
            $fields = $this->getTableField(true);
        }
        if(is_string($fields)){
            $fields = explode(",", $fields);
        }
        if($outFields){
            if(is_string($outFields)){
                $outFields = explode(",", $outFields);
            }
            $fields = array_diff($fields, $outFields);
        }

        $all_size = $rows + 1;
        if(empty($where)){
            $query = $this->select($fields)->forPage($page, $rows);
            $count = $this->count();
        } else{
            if(is_array($where)){
                // 查询  ->recycle()  ->orderby($order)
                $query = $this->where($where)->select($fields)->forPage($page, $rows);
                $count = $this->where($where)->count();
            } elseif(is_string($where)){
                // 查询  ->recycle()  ->orderby($order)
                $query = $this->whereRaw($where)->select($fields)->forPage($page, $rows);
                $count = $this->whereRaw($where)->count();
            } /*else{
                // 查询  ->recycle()  ->orderby($order)
                $query = $where->select($fields)->forPage($page, $rows);
                $count = $where->count();
            }*/
        }


        if(is_array($order)){
            $query = $query->orderBy($order[0], $order[1]);
        } else{
            $query = $query->orderByRaw($order);
        }

        // 查找过滤
        $is_next = 0;
        $lists   = $query->get()->toArray();
        // 查看是否需要翻页
        if($page * $rows < $count){
            $is_next = 1;
        }

        // 过滤json
        $jsonField = isset($this->jsonField) ?: '';
        if(!empty($jsonField)){
            $jsonField = is_string($jsonField) ? explode(',', $jsonField) : $jsonField;
            foreach($lists as $_list){
                foreach($jsonField as $_field){
                    $_list->$_field = json_decode($_list->$_field, 1);
                }
            }
        }

        // 返回编辑作者
        $uids = array_unique(array_column($lists, 'uid'));
        if($uids){
            $userDb = new User();
            $users  = $userDb->isCache(true)->getListInIds($uids);
            foreach($lists as &$item){
                $_uid = $item['uid'];
                // 整理
                $item['user'] = $users[$_uid] ?? [];
                // 头像
                if($item['user']){
                    $item['user']['head_img'] = $this->getFullUrl($item['user']['head_img']);
                }
            }
        }


        $result = ['total' => $count, 'page' => $page, 'rows' => $rows, 'is_next' => $is_next, 'list' => $lists,];
        // 保存为缓存
        if($is_cache){
            $this->addCacheList($lists, $cacheName, $result, 'list');
        }

        return $result;
    }


    // 删除文章
    public function softDelete($where)
    {
        $lists = $this->isCache(true)->getList($where);  //->recycle()
        if(empty($lists)){
            return $this->return_false('你要删除的数据不存在！！');
        }

        $_ids = array_column($lists, 'id');
        $ntDb = new NewsTopic();
        $ncDb = new NewsCate();
        $nsDb = new NewsSite();
        // 查找有关的话题
        $ntLists = $ntDb->whereIn('news_id', $_ids)->get()->toArray();
        $topNum  = [];
        foreach($ntLists as $item){
            $_topicId = $item['topic_id'];
            // 重新整理
            $topNum[$item['news_id']][$_topicId] = ($topNum[$item['news_id']][$_topicId] ?? 0) + 1;
        }
        // 查找有关的栏目
        $ncLists = $ncDb->whereIn('news_id', $_ids)->get()->toArray();
        $cateNum = [];
        foreach($ncLists as $item){
            $_cateId = $item['cate_id'];
            // 重新整理
            $cateNum[$item['news_id']][$_cateId] = ($cateNum[$item['news_id']][$_cateId] ?? 0) + 1;
        }
        // 查找有关的用户
        $userNum = [];
        foreach($lists as $item){
            $_uid = $item['uid'];
            // 重新整理
            $userNum[$item['id']][$_uid] = ($userNum[$item['id']][$_uid] ?? 0) + 1;
        }
        // 查找阿特的用户
        $_channels = array_column($lists, 'channel', 'id');
        $nuLists   = $nsDb->whereIn('news_id', $_ids)->get()->toArray();
        $nuserNum  = [];

        $addonDb = new NewsAddon();
        $userDb  = new User();
        $topicDb = new Topic();
        $cateDb  = new SiteCate();
        DB::beginTransaction();
        try{
            // 删除文章附件，属性，日志，评论
            $this->whereIn('id', $_ids)->update(['verify' => -1]);
            $addonDb->whereIn('news_id', $_ids)->update(['verify' => -1]);

            // 减少话题
            if($topNum){
                foreach($topNum as $_newsId => $nItem){
                    $_channel = $_channels[$_newsId] ?? '';
                    if(empty($_channel)){
                        continue;
                    }
                    foreach($nItem as $_id => $_num){
                        if(empty($_num)){
                            continue;
                        }
                        $topicDb->where('id', $_id)->where($_channel.'_no', '>=', $_num)->update([$_channel.'_no' => DB::raw($_channel."_no-".$_num)]);
                    }
                }
            }

            // 减少栏目
            /*if($cateNum){
                foreach($cateNum as $kk => $nn){
                    $nsDb->where('id', $kk)->update(['news_no' => DB::raw("news_no-".$nn)]);
                }
            }*/

            // 减少用户文章数量
            if($userNum){
                foreach($userNum as $_newsId => $nItem){
                    $_channel = $_channels[$_newsId] ?? '';
                    if(empty($_channel)){
                        continue;
                    }
                    foreach($nItem as $_id => $_num){
                        if(empty($_num)){
                            continue;
                        }
                        $userData = [
                            $_channel.'_no' => DB::raw($_channel."_no-".$_num),
                            'publish_no'    => DB::raw("publish_no-".$_num),
                        ];
                        $userDb->where('id', $_id)->where($_channel.'_no', '>=', $_num)->update($userData);
                    }
                }
            }

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 缓存操作
        /*if($cateNum){
            foreach($cateNum as $kk => $nn){
                $nsDb->reSaveCache($kk, ['news_no' => "-".$nn]);
            }
        }*/
        $this->deleteCacheList($lists);
        $this->deleteCacheShow(['id' => $_ids, 'verify' => -1]);
        $userDb->deleteCacheShow(['id' => array_column($lists, 'uid')]);
        if($userNum){
            foreach($userNum as $_newsId => $nItem){
                $_channel = $_channels[$_newsId] ?? '';
                if(empty($_channel)){
                    continue;
                }
                foreach($nItem as $_id => $_num){
                    if(empty($_num)){
                        continue;
                    }
                    $userCache = [$_channel.'_no' => "-".$_num, 'publish_no' => "-".$_num,];
                    //$userDb->reSaveCache($_id, $userCache);
                    $userDb->deleteCacheShow(['id' => $_id]);
                }
            }
        }
        if($topNum){
            foreach($topNum as $_newsId => $nItem){
                $_channel = $_channels[$_newsId] ?? '';
                if(empty($_channel)){
                    continue;
                }
                foreach($nItem as $_id => $_num){
                    if(empty($_num)){
                        continue;
                    }
                    //$topicDb->reSaveCache($_id, [$_channel.'_no' => "-".$_num]);
                    $topicDb->deleteCacheShow(['id' => $_id]);
                }
            }
        }

        return true;
    }

    // 文件地址
    protected function getFullUrl($url)
    {
        if(!$url) return '';
        if(substr($url, 0, 4) != 'http'){
            $domain = Config::get('site.cdnHost');
            $domain = substr($domain, -1) == '/' ? substr($domain, 0, -1) : $domain;
            $url    = $domain.$url;
        }

        return $url;
    }

    // 定义验证操作
    public function rules()
    {

        $add = [
        ];

        $edit = [
        ];

        $info = [
        ];


        $rule = [
            // 详情
            // 'content'     => 'required',

            'title'        => 'required',
            'from_channel' => 'sometimes|required',
            'from_site'    => 'required',
            'description'  => 'required',
            'from_url'     => 'required',
            'author'       => 'sometimes|required',
            //'keyword'     => 'required',
            // 本表
            'pic'          => 'sometimes|required',
            'uid'          => 'numeric',
            'cate_id'      => 'numeric',
            'read_no'      => 'numeric',
            'virtual_no'   => 'numeric',
            'praise_no'    => 'numeric',
            'collect_no'   => 'numeric',
            'relay_no'     => 'numeric',
            'is_top'       => 'numeric',
            'verify'       => ['in:0,1'],
            //'status'      => ['in:0,1,2'],
            //'is_original' => 'numeric',
            //'images'      => 'required',
            //'ip'          => 'required',
            //'ip_address'  => 'required',
            //'is_push'     => 'required',
        ];


        $msg = [
            'id'           => '自编号',
            'title'        => '标题',
            'uid'          => '用户id',
            'to_uid'       => '对某个人说',
            'pic'          => '图片',
            'cate_id'      => '栏目id',
            'author'       => '作家',
            'from_site'    => '来源站点',
            'from_channel' => '来源频道',
            'keyword'      => '关键字',
            'description'  => '描述(现在快讯最多588个字)',
            'read_no'      => '浏览数',
            'virtual_no'   => '虚拟浏览数',
            'praise_no'    => '点赞数',
            'collect_no'   => '收藏数',
            'relay_no'     => '转发次数',
            'images'       => '图片集合',
            'verify'       => '是否审核（1-是，-1删除）',
            'ip'           => 'ip地址',
            'ip_address'   => 'ip的实际地址',
            'is_top'       => '是否置顶（1-是）',
            'is_push'      => '是否推送（1-是）',
            'from_url'     => '采集文章的来源地址',
            'ctime'        => '创建时间',
            'mtime'        => '修改时间',
        ];

        return ['rule' => $rule, 'msg' => $msg, 'add' => $add];
    }

}
